﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace newsteadWebService.Models
{
    class DBDataBase
    {
        protected SqlConnection SqlCon;
        //1st create sqlconnection
        public bool OpenConnection(string Connection = "DefaultConnection")
        {
            //this is query for connection to database
            SqlCon = new SqlConnection(@WebConfigurationManager.ConnectionStrings[Connection].ToString());
            try
            {
                bool Test = true;
                //if = open it will open connection
                if (SqlCon.State.ToString() != "open")
                {
                    SqlCon.Open();
                }
                return Test;
            }
            catch (Exception ex)
            {
                //when it can not open
                return false;
            }
        }
        public bool CloseConnection()
        {
            try
            {
                SqlCon.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        // this function for insert to table
        public int DBInsert(string sql)
        {
            int lastid = 0;
            //this it select last id for return
            string query = sql + "; SELECT @@identity;";
            try {
                if (SqlCon.State.ToString() == "open")
                {
                    // make excute string query
                    SqlCommand cmd = new SqlCommand(query, SqlCon);
                    // get last id
                    lastid = this.ToINT(cmd.ExecuteScalar());
                }
                return this.ToINT(lastid);
            }
            catch {
                return 0;
            }
        }

        //this fuction for convert to integer
        public int ToINT(object s)
        {
            try 
            {
                return Int32.Parse(s.ToString());
            }
            catch 
            {
                return 0; 
            }
        }
    }
}
